package cn.nosql.tools;

import cn.nosql.rpc.MyRpcService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.nio.ByteBuffer;
import java.util.List;

public class MyClient {

    private TTransport transport = new TFramedTransport(new TSocket("127.0.0.1", 8091));
    private TProtocol protocol = new TCompactProtocol(transport);

    private MyRpcService.Client client = new MyRpcService.Client(protocol);

    public String executeSqlQuery(String sql)
    {
        try {
            transport.open();
            return client.executeSqlQuery(sql);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            transport.close();
        }
        return null;
    }

    public List<Byte> insertNoSql(String cache_name, String method_name, List<Byte> key, List<Byte> value)
    {
        try {
            transport.open();
            return client.insertNoSql(cache_name, method_name, key, value);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            transport.close();
        }
        return null;
    }

    public List<Byte> executeNoSql(String cache_name, String method_name, List<Byte> key)
    {
        try {
            transport.open();
            return client.executeNoSql(cache_name, method_name, key);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            transport.close();
        }
        return null;
    }
}

